package com.browsesoft.resource;

import java.sql.SQLException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;

import com.browsesoft.Manager;
import com.browsesoft.dbtools.DBTools;

/**
 * 权限管理器
 */
public class RightManager implements Manager {
	/**
	 * 
	 */
	private static final long serialVersionUID = -1131294171153053020L;

	// 权限列表
	private LinkedList rights = new LinkedList();

	// 自己
	private static RightManager rightManager = new RightManager();

	public RightManager() {
		rightManager = this;
	}

	public static RightManager getRightManager() {
		return rightManager;
	}

	public void addRight(Right r) {
		rights.add(r);
	}

	public void remove(Right r) {
		rights.remove(r);
	}

	public Right getRight(String id) {
		for (int i = 0; i < rights.size(); i++) {
			Right right = (Right) this.rights.get(i);
			if (right.getID().equals(id)) {
				return right;
			}
		}
		return null;
	}

	public void load() throws Exception {
		try {
			String[][] result = DBTools
					.executeQueryWithTableHead("select * from t_right");
			for (int j = 1; j < result.length; j++) {
				// 取出属性值
				Hashtable hash = DBTools.getAttributes(result, j);
				Right right = new Right(hash);
				this.addRight(right);
			}
		} catch (SQLException e) {
			// 初始表不存在，不用管
		}
	}

	public Object getObject(String id) {
		for (int i = 0; i < rights.size(); i++) {
			Right right = (Right) this.rights.get(i);
			if (right.getID().equals(id)) {
				return right;
			}
		}
		return null;
	}

	/**
	 * 根据资源得到所有权限
	 * 
	 * @param res
	 * @return
	 */
	public LinkedList getRightsByResource(Resource res) {
		LinkedList result = new LinkedList();
		Iterator ite = rights.iterator();
		while (ite.hasNext()) {
			Right right = (Right) ite.next();
			BasicResource rs = (BasicResource) right.getResource();
			if (rs != null && rs.equals(res)) {
				result.add(right);
			}
		}
		return result;
	}

	public void synchronAdd(String className, Hashtable attributes) {
		// TODO Auto-generated method stub

	}

	public void synchronRemove(String id) {
		// TODO Auto-generated method stub

	}

	public void synchronUpdate(String id, Hashtable attributes) {
		// TODO Auto-generated method stub

	}
}